#README contents:
#:include: ../README
module TypoPermalinkWithId #:nodoc:
  #When instantiated in init.rb attaches an after_create to article to modify the permalink 
  class ArticleObserver < ActiveRecord::Observer
    observe Article
    #After an article is created prefix the id and a hyphen, and resave.
    def after_create(article)
      article.permalink = "#{article.id}-#{article.permalink}"
      article.save
    end
  end
  
  #When included modifies how permalink finds an article
  module ModifyArticlesController
    #Alias the original method, permalink, to the new modified_permalink
    def self.included(base)
      base.class_eval do
        alias_method :permalink, :modified_permalink
      end
    end
    #First try to find the article as usual, by full permalink, since that will find both articles
    #in the new scheme, and links to articles in the old scheme.  Then if not found try to find by id
    #and redirect to the correct permalink.  If that doesn't work, it is probably an old link to an
    #updated article, so search by the title without the prefix.  If all else fails, the display_article
    #call with null will show the default Typo "post not found" error, as before.
    def modified_permalink
      article = this_blog.published_articles.find_by_permalink(*params.values_at(:year, :month, :day, :title))
      redirect_to article.permalink_url and return if article.nil? and article = Article.find_by_id(params[:title].to_i)
      redirect_to article.permalink_url and return if article.nil? and article = Article.find_by_title(params[:title])
      display_article(article)
    end
  end
end
